<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="指导老师姓名" prop="instructor">
        <el-input
          v-model="queryParams.instructor"
          placeholder="请输入姓名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" prop="id" :show-overflow-tooltip="true" />
      <el-table-column
        label="获奖学生姓名"
        prop="createName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="指导老师" prop="instructor" />
      <el-table-column label="赛项" prop="title" />
      <el-table-column label="学生证" align="center" prop="image" width="180">
        <template slot-scope="scope">
          <el-image
            style="width: 200px; height: 150px"
            @click.stop="max(scope.row.image)"
            :src="scope.row.image"
          ></el-image>
          <!-- <el-avatar @click.stop="max(scope.row.image)" shape="square" :src="scope.row.image" :size=100></el-avatar> -->
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-if="scope.row.id !== 1" slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :current-page.sync="queryParams.pageNum"
      @current-change="getCertificate"
      @size-change="getCertificate"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="获奖赛项" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入获奖赛项"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="获奖人员">
              <el-input
                v-model="form.createName"
                placeholder="请输入获奖人员"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指导老师">
              <el-input
                v-model="form.instructor"
                placeholder="请输入指导老师"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否置顶">
              <el-radio-group v-model="form.isTop">
                <el-radio :key="1" :label="1">是</el-radio>
                <el-radio :key="0" :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" />

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缩略图">
              <el-upload
                :file-list="fileList"
                class="upload-demo"
                list-type="picture"
                drag
                name="img"
                action="upload"
                :on-remove="fileRemove"
                :limit="1"
                :http-request="handleUpload"
                :on-exceed="onExceed"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过2M
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSubmit">{{
                this.form.id > 0 ? "修改" : "添加"
              }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      width="60%"
      :show-close="false"
      center
    >
      <div style="text-align:center;">
        <el-image :src="maxImage"></el-image>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/menu";
import {
  listCertificate,
  delCertificate,
  addCertificate,
  qeuryCertificate,
  updateCertificate,
} from "@/api/studio/certificate";
import { uploadImg } from "@/api/content/upload";
export default {
  name: "Certificate",
  data() {
    return {
      form: {
        title: "",
        image: "",
        instructor: "",
        // isComment: '0',
        createName: "",
        isTop: 0,
        id: 0,
      },
      //上传图片文件
      fileList: [],
      //点击放大图片的dalog
      dialogVisible: false,
      //Dialog的控制
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //需要放大显示的图片
      maxImage: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜单列表
      menuOptions: [],
      menuExpand: false,
      menuNodeAll: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        instructor: undefined,
      },
      // 表单参数
      // form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCertificate();
  },
  methods: {
    onExceed() {
      this.$message.error("只能上传一个图片");
    },
    handleUpload(img) {
      uploadImg(img.file)
        .then((response) => {
          this.form.image = response;
          this.fileList.push({ name: img.file.name, url: response });
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    fileRemove(file, fileList) {
      this.fileList.pop();
    },
    // 绑定@imgAdd event
    addImg(pos, file) {
      // 第一步.将图片上传到服务器.
      uploadImg(file)
        .then((response) => {
          this.$refs.md.$img2Url(pos, response);
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    //放大图片
    max(image) {
      this.maxImage = image;
      this.dialogVisible = true;
    },
    // 查询所有的申请
    getCertificate() {
      this.loading = true;
      listCertificate(this.queryParams).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //   /** 查询角色列表 */
    //   getList() {
    //     this.loading = true
    //     listRole(this.queryParams).then((response) => {
    //       this.roleList = response.rows
    //       this.total = response.total
    //       this.loading = false
    //     })
    //   },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(id) {
      return roleMenuTreeselect(id).then((response) => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    // 角色状态修改
    handleStatusChange(row) {
      const text = row.status === 0 ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.roleName + '"角色吗？')
        .then(function () {
          return changeRoleStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === 0 ? 1 : 0;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    //   reset() {
    //     if (this.$refs.menu !== undefined) {
    //       this.$refs.menu.setCheckedKeys([])
    //     }

    //     // eslint-disable-next-line no-sequences
    //     (this.menuNodeAll = false),
    //     (this.menuExpand = false),
    //     (this.form = {
    //       id: undefined,
    //       roleName: undefined,
    //       roleKey: undefined,
    //       roleSort: 0,
    //       status: '0',
    //       menuIds: [],
    //       remark: undefined
    //     })
    //     this.resetForm('form')
    //   },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getCertificate();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      const treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    reset() {
      this.form.title = "";
      this.form.image = "";
      this.form.instructor = "";
      this.form.createName = "";
      this.form.isTop = 0;
      this.form.id = 0;
      this.fileRemove();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.reset();
      this.title = "添加证书";
    },
    handleSubmit() {
      if (this.form.id > 0) {
        updateCertificate(this.form).then((response) => {
          if (response.code == 200) {
            this.$message.success("修改成功");
            this.reset();
            this.open = false;
            this.getCertificate();
          } else {
            this.$message.error(response.msg);
          }
        });
      } else {
        addCertificate(this.form).then((response) => {
          if (response.code == 200) {
            this.$message.success("添加成功");
            this.reset();
            this.open = false;
            this.getCertificate();
          } else {
            this.$message.error(response.msg);
          }
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.reset();
      qeuryCertificate(row.id).then((response) => {
        this.form = response;
        this.fileList.push({ name: "获奖证书", url: response.image });
      });
    },
    /** 提交按钮 */

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除角色学号为"' + ids + '"的数据项？')
        .then(function () {
          return delCertificate(ids);
        })
        .then(() => {
          this.getCertificate();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
  